package template2

import (
	"bytes"
	"fmt"
	"gitee.com/chejiangyi/bsfgo/core/base2"
	"gitee.com/chejiangyi/bsfgo/core/utils"
	"html/template"
	"strings"
	"sync"
)

var (
	templateCache          = make(map[string]*template.Template)
	mutex                  = &sync.RWMutex{}
	ShardTemplateFileNames []string
	TemplateUtil           = &TemplateUtilTool{}
)

type TemplateUtilTool struct{}

func (*TemplateUtilTool) TryGetTemplateFromCache(tmplName string, filename []string) *template.Template {
	mutex.RLock()
	tmpl, ok := templateCache[tmplName]
	mutex.RUnlock()

	if ok {
		return tmpl
	}

	// 未缓存则解析
	filename = append(filename, ShardTemplateFileNames...)
	filename = utils.FileUtil.FilterNoExistingFiles(filename)
	tmpl, err := template.ParseFiles(filename...)
	if err != nil {
		panic(base2.NewBsfError2(fmt.Sprintf("模板解析失败:%s(模板文件:%v)", tmplName, strings.Join(filename, ",")), err))
	}

	mutex.Lock()
	templateCache[tmplName] = tmpl
	mutex.Unlock()

	return tmpl
}

func (m *TemplateUtilTool) RenderTemplate(buf *bytes.Buffer, tmplName string, tmpl *template.Template, data interface{}) {
	err := tmpl.ExecuteTemplate(buf, tmplName, data)
	if err != nil {
		panic(base2.NewBsfError2(fmt.Sprintf("模板渲染失敗:%s(此页面缓存模板:%s)", tmplName, m.PrintTemplate(tmpl)), err))
	}
}

func (*TemplateUtilTool) PrintTemplate(tmpl *template.Template) string {
	var buf strings.Builder
	for _, tmpl := range tmpl.Templates() {
		buf.WriteString(tmpl.Name())
		buf.WriteString(" ")
	}
	return buf.String()
}
